package com.goldcn.orderborrow.service;

import com.goldcn.common.CommonTools;
import com.goldcn.common.HttpUtil;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ErpBorrowInterfaceCfg;
import com.goldcn.config.ProConstants;
import com.goldcn.enumeration.ErpInterfaceCfgEnum;
import com.goldcn.enumeration.ErrorCodeEnum;
import com.goldcn.goods.service.GoodsService;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.erpVo.ResultData;
import com.goldcn.order.service.OrderService;
import com.goldcn.orderborrow.dao.OrderBorrowAuditMapper;
import com.goldcn.orderborrow.dao.OrderBorrowItemMapper;
import com.goldcn.orderborrow.dao.OrderInfoBorrowMapper;
import com.goldcn.orderborrow.erpbean.BorrowInfoWithItems;
import com.goldcn.orderborrow.model.OrderBorrowAudit;
import com.goldcn.orderborrow.model.OrderBorrowItem;
import com.goldcn.orderborrow.model.OrderInfoBorrow;
import com.goldcn.orderborrow.vo.OrderBorrowAuditVo;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Description:借货审核业务类
 * @Author Tim Peng
 * @date 2017-4-20 17:21:01
 * @version V1.0
 */
@Service
public class OrderBorrowAuditService {

    @Autowired
    private OrderBorrowAuditMapper orderBorrowAuditMapper;

    @Autowired
    OrderInfoBorrowMapper orderInfoBorrowMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    OrderBorrowItemMapper orderBorrowItemMapper;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderBorrowService orderBorrowService;

    @Autowired
    ErpBorrowInterfaceCfg erpBorrowInterfaceCfg;

    @Autowired
    OrderService orderService;

    private static Logger logger = LoggerFactory.getLogger(OrderBorrowAuditService.class);

    /**
     * 审核借货;1.上级审核(批量)
     * @param orderBorrowAuditVoList
     * @return
     */
    @Transactional
    public Object borrowAuditStepOne(List<OrderBorrowAuditVo> orderBorrowAuditVoList) throws Exception {
        Integer ret=0;
        for(OrderBorrowAuditVo orderBorrowAuditVo:orderBorrowAuditVoList){
            //获取借货审核设置
            String orderBorrowAuditLevel=getBorrowSetting(orderBorrowAuditVo.getCompanyID());
            if(!"2".equals(orderBorrowAuditLevel)){
                throw CommonTools.createException(ErrorCodeEnum.noSettingOrderBorrowAuditLevel);
            }
            if("1".equals(orderBorrowAuditLevel)){//1表示已设置无需上级审核
                throw CommonTools.createException(ErrorCodeEnum.orderBorrowAuditException);
            }
            OrderInfoBorrow orderInfoBorrow =
                    orderInfoBorrowMapper.selectByPrimaryKey(orderBorrowAuditVo.getOrderID());
            if(orderInfoBorrow==null){
                throw CommonTools.createException(ErrorCodeEnum.orderBorrowNoExist);
            }
            if(1!=orderInfoBorrow.getState()){
                throw CommonTools.createException(ErrorCodeEnum.orderBorrowStateError);
            }
            OrderInfoBorrow orderBorrowSave=new OrderInfoBorrow();
            orderBorrowSave.setId(orderInfoBorrow.getId());
            orderBorrowSave.setFastAuditTime(CommonUtils.getCurTimestamp());
            orderBorrowSave.setState(orderBorrowAuditVo.getState());
            orderInfoBorrowMapper.updateByPrimaryKeySelective(orderBorrowSave);

            //审核拒绝+sku库存
            if(20==orderBorrowAuditVo.getState() || 30==orderBorrowAuditVo.getState()){
                List<OrderBorrowItem> itemList = orderBorrowItemMapper.selectByOrderID(orderInfoBorrow.getId());
                for (OrderBorrowItem item : itemList) {
                    goodsService.changeInventory(2, item.getGoodsID(), item.getSkuID(), item.getQty());
                }
            }

            OrderBorrowAudit orderBorrowAudit=new OrderBorrowAudit();
            BeanUtils.copyProperties(orderBorrowAudit, orderBorrowAuditVo);
            orderBorrowAudit.setId(IdGen.get().nextId());
            orderBorrowAudit.setAddTime(CommonUtils.getCurTimestamp());
            orderBorrowAudit.setCompanyID(SystemContext.getCompanyID());
            ret+= orderBorrowAuditMapper.insertSelective(orderBorrowAudit);

            if(21==orderBorrowAuditVo.getState()){//审核通过,请求同步ERP
                borrowSendToERP(orderBorrowAuditVo.getOrderID());
            }

        }
        return ret;
    }

    /**
     * 审核借货;2.系统审核(批量)
     * @param orderBorrowAuditVoList
     * @return
     */
    @Transactional
    public Object borrowAuditStepTwo(List<OrderBorrowAuditVo> orderBorrowAuditVoList) throws Exception {
        Integer ret=0;
        for(OrderBorrowAuditVo orderBorrowAuditVo:orderBorrowAuditVoList) {
            //获取借货审核设置
            String orderBorrowAuditLevel = getBorrowSetting(orderBorrowAuditVo.getCompanyID());
            OrderInfoBorrow orderInfoBorrow =
                    orderInfoBorrowMapper.selectByPrimaryKey(orderBorrowAuditVo.getOrderID());
            if (orderInfoBorrow == null) {
                throw CommonTools.createException(ErrorCodeEnum.orderBorrowNoExist);
            }
            if(1!=orderBorrowAuditVo.getOrganizationalLevel()){//总部员工直接系统审核
                switch (orderBorrowAuditLevel) {
                    case "1"://1.系统审核
                        if (1 != orderInfoBorrow.getState()
                                || 21 != orderInfoBorrow.getState()) {
                            throw CommonTools.createException(ErrorCodeEnum.orderBorrowStateError);
                        }
                        break;
                    case "2"://2.上级+系统审核
                        if (21 != orderInfoBorrow.getState()) {
                            throw CommonTools.createException(ErrorCodeEnum.orderBorrowStateError);
                        }
                        break;
                    default:
                        throw CommonTools.createException(ErrorCodeEnum.noSettingOrderBorrowAuditLevel);
                }
            }
            OrderInfoBorrow orderBorrowSave = new OrderInfoBorrow();
            orderBorrowSave.setId(orderInfoBorrow.getId());
            orderBorrowSave.setLastAuditTime(CommonUtils.getCurTimestamp());
            orderBorrowSave.setState(orderBorrowAuditVo.getState());
            orderInfoBorrowMapper.updateByPrimaryKeySelective(orderBorrowSave);
            //审核拒绝+库存
            if(20==orderBorrowAuditVo.getState() || 30==orderBorrowAuditVo.getState()){
                List<OrderBorrowItem> itemList = orderBorrowItemMapper.selectByOrderID(orderInfoBorrow.getId());
                for (OrderBorrowItem item : itemList) {
                    goodsService.changeInventory(2, item.getGoodsID(), item.getSkuID(), item.getQty());
                }
            }else{
                List<OrderBorrowItem> itemList = orderBorrowItemMapper.selectByOrderID(orderInfoBorrow.getId());
                for (OrderBorrowItem item : itemList) {
                    goodsService.changeInventory(1, item.getGoodsID(), item.getSkuID(), item.getQty());
                }
            }
            OrderBorrowAudit orderBorrowAudit = new OrderBorrowAudit();
            BeanUtils.copyProperties(orderBorrowAudit, orderBorrowAuditVo);
            orderBorrowAudit.setId(IdGen.get().nextId());
            orderBorrowAudit.setAddTime(CommonUtils.getCurTimestamp());
            orderBorrowAudit.setCompanyID(SystemContext.getCompanyID());
            ret+= orderBorrowAuditMapper.insertSelective(orderBorrowAudit);
        }
        return ret;
    }

    /**
     * 审核借货;2.系统审核(For ERP)
     * @param orderBorrowAuditVoList
     * @return
     */
    @Transactional
    public Object borrowAuditForERP(OrderBorrowAuditVo orderBorrowAuditVoList) throws Exception {
        Integer ret=0;
        logger.info("ERP开始审核借货订单");
//        orderBorrowAuditVoList.setCompanyID(ProConstants.COMPANY_ID);
        OrderInfoBorrow orderInfoBorrow =
                orderInfoBorrowMapper.selectByPrimaryKey(orderBorrowAuditVoList.getOrderID());
        orderBorrowAuditVoList.setCompanyID(orderInfoBorrow.getCompanyID());
        if (orderInfoBorrow == null) {
            throw CommonTools.createException(ErrorCodeEnum.orderBorrowNoExist);
        }
        if (1 != orderInfoBorrow.getState() && 21!= orderInfoBorrow.getState()) {
            throw CommonTools.createException(ErrorCodeEnum.orderBorrowStateError);
        }
        OrderInfoBorrow orderBorrowSave = new OrderInfoBorrow();
        orderBorrowSave.setId(orderInfoBorrow.getId());
        orderBorrowSave.setLastAuditTime(CommonUtils.getCurTimestamp());
        orderBorrowSave.setState(orderBorrowAuditVoList.getState());
        orderBorrowSave.setRemark(orderBorrowAuditVoList.getRemark());
        orderInfoBorrowMapper.updateByPrimaryKeySelective(orderBorrowSave);
        //审核拒绝+库存
        if(20==orderBorrowAuditVoList.getState() || 30==orderBorrowAuditVoList.getState()){
            List<OrderBorrowItem> itemList = orderBorrowItemMapper.selectByOrderID(orderInfoBorrow.getId());
            for (OrderBorrowItem item : itemList) {
                goodsService.changeInventory(2, item.getGoodsID(), item.getSkuID(), item.getQty());
            }
        }else{
            List<OrderBorrowItem> itemList = orderBorrowItemMapper.selectByOrderID(orderInfoBorrow.getId());
            for (OrderBorrowItem item : itemList) {
                goodsService.changeInventory(1, item.getGoodsID(), item.getSkuID(), item.getQty());
            }
        }
        OrderBorrowAudit orderBorrowAudit = new OrderBorrowAudit();
        BeanUtils.copyProperties(orderBorrowAudit, orderBorrowAuditVoList);
        orderBorrowAudit.setId(IdGen.get().nextId());
        orderBorrowAudit.setAddTime(CommonUtils.getCurTimestamp());
        orderBorrowAudit.setAuditName("FROM_ERP");//固定ERP审核用户名
        ret+= orderBorrowAuditMapper.insertSelective(orderBorrowAudit);
        logger.info("ERP审核借货成功,orderID:" + orderBorrowAuditVoList.getOrderID());
        return ret;
    }

    /**
     * 同步借货订单
     * TO ERP
     * @param orderID
     * @return
     */
    public void borrowSendToERP(Long orderID){
        if (orderService.isOpenErp()) {//调用ERP接口,同步订单
            logger.info("开始同步借货订单ERP信息");
            BorrowInfoWithItems erpBorrowVo = (BorrowInfoWithItems)
                    orderBorrowService.selectOrderBorrowErp(orderID);
            if (null==erpBorrowVo){
                throw CommonTools.createException(ErrorCodeEnum.borrowToERPNofoundException);
            }
            ResultData res =  CommonTools.getExchangeData(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ADDORDERERP.getCode()), erpBorrowVo, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()));
            if ("1".equals(res.getCode())) {
                logger.info("借货订单同步ERP信息成功,orderID:" + orderID);
            }else if("1003".equals(res.getCode())){
                logger.info("重复同步,借货订单之前已同步,orderID:" + orderID);
            }else{
                logger.info("借货订单同步ERP信息失败:"+res.getMessage()+"/n"+res.getCode());
                System.out.println(res.getMessage() + ":" + res.getCode());
                throw CommonTools.createException(ErrorCodeEnum.borrowToERPFailure);
            }
        }
    }

    /**
     * 借货订单收货
     * TO ERP
     * @param orderID
     * @return
     */
    public void borrowReceiptToERP(Long orderID){
        if (orderService.isOpenErp()) {//调用ERP接口,确认收货
            logger.info("开始确认收货借货订单ERP信息");
            ResultData res = CommonTools.httpGet(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.RECEIVEDERP.getCode()) + "?borrowNO=" + orderID, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()));
            if ("1".equals(res.getCode())) {
                logger.info("借货确认收货同步ERP信息成功,orderID:" + orderID);
            }else if("1003".equals(res.getCode())){
                logger.info("重复确认收货,借货订单之前已同步,orderID:" + orderID);
            }else{
                logger.info("借货订单确认收货ERP信息失败:"+res.getMessage()+"/n"+res.getCode());
                System.out.println(res.getMessage() + ":" + res.getCode());
                throw CommonTools.createException(ErrorCodeEnum.borrowToERPReceiptFailure);
            }
        }
    }

    /**
     * 获取借货设置
     * @param companyID
     * @return
     */
    private String getBorrowSetting(Long companyID){
        DataResult result = HttpUtil.httpGet(//获取借货订单审核级别
                ProConstants.getOrderBorrowAuditLevel + companyID, restTemplate);
        return result.getIsSuccess() == 1?result.getData().toString():"";
    }


    public OrderBorrowAudit selectByPrimaryKey(Long id){
        return orderBorrowAuditMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询订单审核记录
     * @param orderID
     * @return
     */
    public Object selectByOrderID(Long orderID){
        return orderBorrowAuditMapper.selectByOrderID(orderID);
    }


}
